<?php

define ('AEDITUUS_ROOT', '../');
require_once AEDITUUS_ROOT.'commun.php';

// L'objet user, demarrage de la session utilisateur
$user = new AeUser();
$user->session_begin();
$userData = $user->getUserData();

// L'objet bdd, demarrage de la session bdd
$db = db::getInstance();

// On recupere la config generale
$data = array(
    'pseudo' => (isset($user->pseudo) ? $user->pseudo : ''),
    'email' => (isset($user->email) ? $user->email : ''),
    'form_brut' => basename(__FILE__),
    'AEDITUUS_ROOT' => AEDITUUS_ROOT,
    'user' => $user
);

$result = $db->get_array( "SELECT name, value FROM ".$cfg['prefix']."config" );
foreach ($result as $config)
{
    $data[$config->name] = $config->value;
}
//global $user, $cfg;
// On check le statut du user. Pas la peine de gérer le form si de toute façon, il a pas le droit
$checkStatus = $db->get_var("SELECT statut_client FROM ".$cfg['prefix']."users WHERE id=?", array($user->id));

$data['form_msg'] = array();

if ($checkStatus != 'possible') {
    $data['form_msg'][] = 'Vous n’avez plus de possibilité pour le moment, veuillez retenter plus tard.';

} elseif($data['montant_plafond_journee_usd'] >= $data['plafond_jour_usd']) {
    $data['form_msg'][] = 'Le plafond Dollars du jour est atteint, Nouveau plafond à 07h00 Heure de Paris.';

} elseif($data['dispo_service_1'] <= $data['mini_service_4']) {
    $data['form_msg'][] = 'Plus de disponible minimum sur le compte Paypal Euros, essayer plus tard.';

} elseif ( $_SERVER['REQUEST_METHOD'] == 'POST' ) {

    $inputs = array(
        'pseudo' => AeValidator::valid($cfg['validator_pseudo'], array('var' => $_POST['pseudo'])),
        'email' => AeValidator::valid('email', array('var' => $_POST['email'])),
        'mliberty' => AeValidator::valid('alphanum', array('var' => $_POST['mliberty'], 'min' => 7)),
        'mpaypal' => AeValidator::valid('email', array('var' => $_POST['mpaypal'], 'min' => 3)),
        'mont1' => AeValidator::valid('float', array('var' => $_POST['mont1'])),
        'mont1_bis' => AeValidator::valid('float', array('var' => $_POST['mont1_bis'])),
        'mont2' => AeValidator::valid('float', array('var' => $_POST['mont2'])),
        'mont2_bis' => AeValidator::valid('float', array('var' => $_POST['mont2_bis'])),
        'termes' => ( (isset($_POST['termes'])&&($_POST['termes'] == 'termes')) ? true : false),
        'pin' => AeValidator::valid('num', array('var'=>$_POST['pin'], 'min'=>4, 'max'=>4))
    );
    $user_row = $db->get_row("SELECT pseudo, email FROM ".$cfg['prefix']."users WHERE id=?", array($user->id));
    if ($user_row->pseudo != $inputs['pseudo']) {
        $data['form_msg'][] = 'Ce pseudo n\'est pas celui du compte actuel';
    }
    if ($user_row->email != $inputs['email']) {
        $data['form_msg'][] = 'Cet email n\'est pas celui du compte actuel';
    }
    if ($userData['pin'] != $inputs['pin']) {
        $data['form_msg'][] = 'Le code PIN n\'est pas valide';
    }
    if ($inputs['mliberty'] === false) {
        $data['form_msg'][] = 'Le compte Liberty n\'est pas correct';
    }
    if ($inputs['mpaypal'] === false) {
        $data['form_msg'][] = 'Le compte Paypal n\'est pas correct';
    }
    if ( ($inputs['mont1'] < $cfg['mini_service_4']) || ($inputs['mont2'] > $cfg['max_service_4']) ) {
        $data['form_msg'][] = 'Le montant que vous d&eacute;sirez doit &ecirc;tre compris entre '.$cfg['mini_service_4'].' et '.$cfg['max_service_4'];
    }
    if ($inputs['mont2_eu'] > $cfg['dispo_service_1']) {
        $data['form_msg'][] = 'Le montant a recevoir dépasse le solde disponible';
    }
    $banni_lib = $db->get_var("SELECT 1 FROM ".$cfg['prefix']."banni_lib WHERE compte=?", array($inputs['mliberty']));
    if ($db->get_nb_result() == 1) {
        $data['form_msg'][] = 'Votre compte Liberty est bannis';
    }
    $banni_mpaypal = $db->get_var("SELECT 1 FROM ".$cfg['prefix']."banni_paypal WHERE mail=?", array($inputs['mpaypal']));
    if ($db->get_nb_result() == 1) {
        $data['form_msg'][] = 'Votre compte Paypal semble bannis, changer de compte';
    }

    // pcqa on fait pas confiance au js !
    // Math.round( (montant*(100-taxe)) ) / 100;
	
	// Calcule de la taxe variable !
	$inputs['taxeF1'] = ( $cfg['fraisV_eg']/($inputs['mont1']/100) );
	$inputs['taxeF2'] = ( $cfg['fraisV_service_4']/($inputs['mont1']/100) );
	$inputs['taxeF3'] = ( $cfg['fraisV_service_1']/($inputs['mont1']/100) );
	$inputs['taxeFixe'] = ( $inputs['taxeF1'] + $inputs['taxeF2'] + $inputs['taxeF3'] );
	$inputs['taxeV'] = ( $cfg['frais_eg'] + $cfg['frais_service_4'] + $cfg['frais_service_1'] );
	$inputs['taxe'] = round ( (($inputs['taxeFixe'] + $inputs['taxeV'])), 3);

	// Calcule du montants suivant la taxe et le montant demander !
    $inputs['mont2'] = round( ($inputs['mont1']*( (100 - $inputs['taxe'])/100)), 2);

	// Calcule du gain de la commande par service eg compris  !
    $Mtaxe = (($inputs['mont1']/100) * ($cfg['frais_service_4'])) + $cfg['fraisV_service_4'] ;

    $inputs['mont1_bis'] = round ( $inputs['mont1'] - $Mtaxe, 2);
    $inputs['mont2_bis'] = round ( ($inputs['mont2'] + $cfg['fraisV_service_1']) / ((100 - $cfg['frais_service_1'])/100), 2);
	
	// Calcule du taux de change applicable !
	$inputs['taux'] = round ( $cfg['tauxUsdEur'] - (($cfg['tauxUsdEur']/100)*$cfg['frais_eg']),4);
	$inputs['mont2_ter'] = round ( ($inputs['mont2'] * $inputs['taux']), 2);
	
	$inputs['mont2_eu'] = round ( ($inputs['mont2_ter'] + $cfg['fraisV_service_1']) / ((100 - $cfg['frais_service_1'])/100), 2);
	
	$inputs['gain_eg'] = round ( ($inputs['mont1_bis'] - $inputs['mont2_bis']), 3);
	$inputs['gain_lr'] = round ( ( $inputs['mont1'] - $inputs['mont1_bis']), 3);
	$inputs['gain_pp'] = round ( ( $inputs['mont2_eu'] - $inputs['mont2_ter']), 3);
	// Devise utiliser ici pas oublier de changer selon besoin !	
				
	$inputs['devise_de'] = 'USD';
	$inputs['devise_vers'] = 'EUR';
	

	
    // Pas d'erreur, on insert
    if (empty($data['form_msg'])) {

        if ($db->query("
           INSERT INTO ".$cfg['prefix']."transaction
           (Id_client, de_serv, compte_de, devise_de, vers_serv, compte_vers, devise_vers, taux, mont1, mont1_bis, mont2, mont2_bis, mont2_ter, mont2_eu, ip)
           VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", array(
               $user->id, 'LibertyReserve', $inputs['mliberty'], $inputs['devise_de'], 'Paypal', $inputs['mpaypal'], $inputs['devise_vers'], $inputs['taux'], $inputs['mont1'], $inputs['mont1_bis'], $inputs['mont2'], $inputs['mont2_bis'], $inputs['mont2_ter'], $inputs['mont2_eu'], $userData['ip']
           )))
		   
        if ($db->query("
           INSERT INTO ".$cfg['prefix']."gainservices
           (Id_client, de_serv, gain_lr, devise_de, vers_serv, gain_pp, devise_vers, gain_eg)
           VALUES (?, ?, ?, ?, ?, ?, ?, ?)", array(
               $user->id, 'LibertyReserve', $inputs['gain_lr'], $inputs['devise_de'], 'Paypal', $inputs['gain_pp'], $inputs['devise_vers'], $inputs['gain_eg']
           )))
        {
           $db->query("UPDATE ".$cfg['prefix']."users SET statut_client='encours' WHERE id=?", array($user->id));
           $db->query("UPDATE ".$cfg['prefix']."config SET value=value+? WHERE name='montant_plafond_journee_usd'", array($inputs['mont1']));
           $db->query("UPDATE ".$cfg['prefix']."config SET value=value-? WHERE name='dispo_service_1'", array($inputs['mont2_eu']));
           $user->transaction_id = $db->get_insert_id();
           header('Location: com_lrppUE.php');
        }
        // On récupère l'état actuel pour l'écrire dans un fichier
           $result_config = $db->get_array("SELECT * FROM ".$cfg['prefix']."config");
           $str_config = '';
        foreach ($result_config as $config) {
            $str_config .= '$cfg[\''.$config->name."']='".$config->value."';\n";
        }
        $str = "<?php\n// Ne rien mettre ici, Ce fichier est généré dynamiquement\n".$str_config;
        if (!@file_put_contents(AEDITUUS_ROOT.'config/config.php', $str)) {
            $tabNoValid['message'] = 'adm_unabled_to_rewrite';
        }
    } else {
        unset($inputs['mont2']);
        $data = array_merge($data, $inputs);
    }
}

echo render_view ($data, AEDITUUS_ROOT.'lr/template/default/forms_lrppUE.tpl.php', AEDITUUS_ROOT.'lr/template/default/index.tpl.php');
